#include "widget.h"
#include "ui_widget.h"
#include<QTimer>
#include<QKeyEvent>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    mGameview.setSceneRect(QRect(0,0,500,669));

    mScene.setSceneRect(QRect(0,0,500,669));

    mBackGround1.setPixmap(QPixmap(":/jpg/C:/Users/lenovo/Desktop/修改尺寸-BG.jpg"));//背景图片1的路径
    mBackGround2.setPixmap(QPixmap(":/jpg/C:/Users/lenovo/Desktop/修改尺寸-BG.jpg"));//背景图片2的路径

    mPlane.setPixmap(QPixmap(":/jpg/C:/Users/lenovo/Desktop/plane修改尺寸.png"));    //飞机图片路径

    mBackGround2.setPos(0,-mBackGround1.pixmap().height());
    mPlane.setPos(250,334);  //飞机的初始位置


    mScene.addItem(&mBackGround1);
    mScene.addItem(&mBackGround2);
    mScene.addItem(&mPlane);
    mGameview.setScene(&mScene);
    mGameview.setParent(this);
    mGameview.show();


    mBGMoveTimer=new QTimer(this);
    mBGMoveTimer->start(40);
    connect(mBGMoveTimer,&QTimer::timeout,this,&Widget::BGMove);
}



Widget::~Widget()
{
    delete ui;
}
void Widget::BGMove()
{

    mBackGround1.moveBy(0,2);
    mBackGround2.moveBy(0,2);

    if(mBackGround1.y()>mBackGround1.pixmap().height())
    {
        mBackGround1.setY(-mBackGround1.pixmap().height());
    }
    else if(mBackGround2.y()>=mBackGround2.pixmap().height())
    {
        mBackGround2.setY(-mBackGround2.pixmap().height());
    }


}

void Widget::PlaneMove()
{
    for(int keyCode : mKeyList)
    {
        switch (keyCode) {
        case QT::Key_W: mPlane.moveBy(0,-1);break;
        case QT::Key_A: mPlane.moveBy(-1,0);break;
        case QT::Key_S: mPlane.moveBy(0,1);break;
        case QT::Key_D: mPlane.moveBy(1,0);break;    //可以调节移动速度

        }


    }
}

void Widget::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {

        case QT::Key_W:
        case QT::Key_A:
        case QT::Key_S:
        case QT::Key_D:
        mKeyList.append(event->key());
        break;




    }

}

void Widget::keyReleaseEvent(QKeyEvent *event)
{

    if(mKeyList.contains(event->key()))
    {
        mKeyList.removeOne(event->key());

    }

}
